

import java.lang.reflect.Type;

import org.apache.log4j.Logger;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class MessageAdapter implements JsonDeserializer<Message>, JsonSerializer<Message>{
	
	private static Logger logger = Logger.getLogger(MessageAdapter.class.getName());
	
	
	@Override
	public JsonElement serialize(Message m, Type typeOfMessage, JsonSerializationContext context) {
		JsonObject jsonObject = new JsonObject();
		
		jsonObject.addProperty("id", m.getId());

		jsonObject.addProperty("type", m.getMsgType());

		return jsonObject;
	}

	@Override
	public Message deserialize(JsonElement json, Type typeOfMessage, JsonDeserializationContext context) throws JsonParseException {
		
		JsonObject jsonObject = json.getAsJsonObject();
		Message u = new Message();
		
		try{
			String id = jsonObject.get("id").getAsString();
			String type = jsonObject.get("type").getAsString();
			
			u.setId(id);
			u.setMessage(type);
		}catch(Exception e){
			logger.warn("Incorrect Json Received. Check Property Names. Exception: " + e);
			//In case the Json was incorrect for some reason it will be set null, so that the program can not
			//work with an incorrect object whatsoever
			u = null;
		}
		
		return u;
	}

}
